package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.local.PreferencesManager
import com.fishingwithme.android.data.model.ApproveRuleItem
import com.fishingwithme.android.data.model.City
import com.fishingwithme.android.data.model.Comment
import com.fishingwithme.android.data.model.RuleItem
import com.fishingwithme.android.data.model.Spot
import com.fishingwithme.android.data.model.SpotDetail
import com.fishingwithme.android.data.repository.FishingRepository
import com.google.gson.Gson
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class HomeUiState(
    val isLoading: Boolean = true,
    val spotDetail: SpotDetail? = null,
    val comments: List<Comment> = emptyList(),
    val isCommentLoading: Boolean = false,
    val hasMoreComments: Boolean = true,
    val commentPageNum: Int = 1,
    val commentPageSize: Int = 10,
    val error: String? = null,
    val rulesItems: List<ApproveRuleItem> = emptyList(),
    val isRulesLoading: Boolean = false
)

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val repository: FishingRepository,
    private val preferencesManager: PreferencesManager
) : ViewModel() {

    private val _uiState = MutableStateFlow(HomeUiState())
    val uiState: StateFlow<HomeUiState> = _uiState.asStateFlow()

    private var currentSpotId: String? = null

    fun loadSpotDetails(spotId: String) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }

            try {
                val spotFlow =
                    repository.loadUserSpot(spotId)

                spotFlow.collect { result ->
                    result.fold(
                        onSuccess = { spotDetail ->
                            currentSpotId = spotDetail.spotId
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    spotDetail = spotDetail,
                                    error = null
                                )
                            }
                            //loadComments()
                        },
                        onFailure = { throwable ->
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    error = throwable.message ?: "加载钓点详情失败"
                                )
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(
                        isLoading = false,
                        error = e.message ?: "未知错误"
                    )
                }
            }
        }
    }

    fun searchCities(keyword: String, onResult: (List<City>) -> Unit) {
        viewModelScope.launch {
            try {
                repository.searchCities(keyword).collect { result ->
                    result.fold(
                        onSuccess = { cities ->
                            onResult(cities)
                        },
                        onFailure = { throwable ->
                            // Handle error silently or log it
                            println("Failed to search cities: ${throwable.message}")
                        }
                    )
                }
            } catch (e: Exception) {
                // Handle exception
                println("Exception while searching cities: ${e.message}")
            }
        }
    }

    fun getSpotId(): String? {
        return _uiState.value.spotDetail?.spotId
    }

    fun collectSpot(spotId: String) {
        viewModelScope.launch {
            try {
                // First check if credit is available
                repository.checkCreditAvailable(spotId).collect { result ->
                    result.fold(
                        onSuccess = { creditAvailable ->
                            if (creditAvailable.isFulfill == 1) {
                                // Proceed with collection
                                repository.collectSpot(spotId).collect { collectResult ->
                                    collectResult.fold(
                                        onSuccess = {
                                            // Show success message
                                            // Reload spot details
                                            loadSpotDetails(spotId)
                                        },
                                        onFailure = { throwable ->
                                            _uiState.update {
                                                it.copy(error = "收藏失败: ${throwable.message}")
                                            }
                                        }
                                    )
                                }
                            } else {
                                _uiState.update {
                                    it.copy(error = "积分不够: ${creditAvailable.difference}")
                                }
                            }
                        },
                        onFailure = { throwable ->
                            _uiState.update {
                                it.copy(error = "检查积分失败: ${throwable.message}")
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(error = e.message ?: "收藏失败")
                }
            }
        }
    }

    fun loadRulesItems(ruleId: Int = 1) {
        viewModelScope.launch {
            _uiState.update { it.copy(isRulesLoading = true, error = null) }

            try {
                repository.getRulesItems(ruleId).collect { result ->
                    result.fold(
                        onSuccess = { rulesItems ->
                            _uiState.update {
                                it.copy(
                                    isRulesLoading = false,
                                    rulesItems = rulesItems,
                                    error = null
                                )
                            }
                        },
                        onFailure = { throwable ->
                            _uiState.update {
                                it.copy(
                                    isRulesLoading = false,
                                    error = throwable.message ?: "加载规则失败"
                                )
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(
                        isRulesLoading = false,
                        error = e.message ?: "未知错误"
                    )
                }
            }
        }
    }

    fun clearError() {
        _uiState.update { it.copy(error = null) }
    }
}